package leetcode.Fiftyone_to_One_hundred;

public class Test66 {

    public static int[] plusOne(int[] digits) {
        int n = digits.length;
        int carry = 0;
        boolean addCapacity = false;
        for (int i = n-1; i >= 0; i--) {
            if (i == n-1) {
                digits[i] = digits[i] + 1;
            } else {
                digits[i] = digits[i] + carry;
                carry = 0;
            }
            if (digits[i] >= 10) {
                digits[i] = digits[i] % 10;
                carry = 1;
            }
            if (i == 0 && carry == 1) {
                addCapacity = true;
            }
        }
        int[] ans = null;
        if (addCapacity) {
            ans = new int[n+1];
            ans[0] = carry;
            for (int i = 1; i < n+1; i++) {
                ans[i] = digits[i-1];
            }
        } else {
            ans = new int[n];
            ans = digits.clone();
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] num = {9,9,9};
        int[] ans = plusOne(num);
        for (int i = 0; i < ans.length; i++) {
            System.out.print(ans[i]);
        }
    }
}
